package servlets;

import hibernatelogic.HibItems;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import orm.Items;

/**
 * Servlet implementation class DeleteItemServlet
 */
@WebServlet("/delete-item-servlet")
public class DeleteItemServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger loggerDeleteItemServlet = Logger
			.getLogger(DeleteItemServlet.class);

    public DeleteItemServlet() {
        super();
    }
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession sess = request.getSession();
		
		if(((String) sess.getAttribute("UserRole")).equals("2")) {
			
			HibItems hibItems = new HibItems();
			Items item = new Items();
			
			int item_id = Integer.parseInt(request.getParameter("ditem"));
			
			try {
				item = hibItems.getItemByID(item_id);
				hibItems.deleteItem(item);
			} catch (SQLException e) {
				loggerDeleteItemServlet.error("Something wrong with DeleteItemServlet");
			} finally {
				hibItems = null;
				item = null;
				response.sendRedirect("/my-pet-project-0/MDeleteItem.jsp");
			}
			
		} else {
			response.sendError(response.SC_FORBIDDEN);
		}
	}
}
